import 'package:dio/dio.dart';
import 'package:easy_rich_text/easy_rich_text.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:tiktokadult/alert_business/video/video_buy_bottom_sheet.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/hj_model/video_model.dart';
import 'package:tiktokadult/hj_page/community_business/post_detail_page/community_image_page.dart';
import 'package:tiktokadult/hj_page/mine_business/mine_share/mine_share_page.dart';
import 'package:tiktokadult/hj_page/mine_business/mine_vip/mine_charge_coin_page.dart';
import 'package:tiktokadult/hj_page/video/video_player_alert.dart';
import 'package:tiktokadult/hj_utils/api_service/mine_service.dart';
import 'package:tiktokadult/hj_utils/global.dart';
import 'package:tiktokadult/hj_utils/player_util.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:tiktokadult/routers/jump_router.dart';
import 'package:tiktokadult/tools_base/global_store/store.dart';
import 'package:tiktokadult/tools_base/loading/loading_alert_widget.dart';
import 'package:tiktokadult/tools_base/net/api_exception.dart';
import 'package:tiktokadult/tools_base/net/base_resp_bean.dart';
import 'package:tiktokadult/tools_base/widget/net_image_widget.dart';

class PostDetailVideoContent extends StatefulWidget {
  final VideoModel model;

  const PostDetailVideoContent({super.key, required this.model});

  @override
  State<PostDetailVideoContent> createState() => _PostDetailVideoContentState();
}

class _PostDetailVideoContentState extends State<PostDetailVideoContent> {
  bool hasClick = false;

  void pushToPostVideoPage() {
    Get.to(() => VideoPlayerAlert(widget.model.realVideoUrl));
  }

  @override
  Widget build(BuildContext context) {
    if (!widget.model.isVideo() && !widget.model.isSeedPost()) return SizedBox.shrink();

    if (widget.model.sourceURL == null || widget.model.sourceURL?.isEmpty == true) return SizedBox.shrink();
    bool isCoin = !(widget.model.freeArea ?? false) && (widget.model.originCoins != 0);

    Future<bool> _onPay() async {
      try {
        var model = widget.model;
        LoadingAlertWidget.show();
        BaseRespBean data = await MineService.postBuyVideo(model.id, 1);
        LoadingAlertWidget.cancel();
        if (data.isSuccess) {
          globalStore.updateUserInfo();

          return true;
        } else {
          if (data.code == 8000) {
            jumpToWalletPage(tabPosition: 1);
          }
        }
      } on DioException catch (e) {
        LoadingAlertWidget.cancel();
        var error = e.error;
        if (error is ApiException) {
          if (error.code == 8000) {
            jumpToWalletPage(tabPosition: 1);
          } else {
            showToast(error.message);
          }
        } else {
          showToast(e.toString());
        }
        // debugLog('productBuy', e.toString());
      } catch (e) {
        LoadingAlertWidget.cancel();
        // debugLog('postBuyVideo', e.toString());
      }
      return false;
    }

    return Column(
      children: [
        GestureDetector(
          onTap: () async {
            if (hasClick == false) {
              setState(() {
                hasClick = true;
              });
              return;
            }
            if (needBuyPostVideo(widget.model) && hasClick) return;

            if (needBuyPostVideo(widget.model)) {
              if (isCoin) {
                var result = await _onPay();

                if (result == true) {
                  widget.model.vidStatus?.hasPaid = true;
                  setState(() {});
                  pushToPostVideoPage();
                }
              }
            } else {
              pushToPostVideoPage();
            }
          },
          child: Container(
            constraints: BoxConstraints(maxWidth: double.infinity, maxHeight: 220),
            child: AspectRatio(
              aspectRatio: 391 / 220,
              child: Stack(
                alignment: Alignment.center,
                children: [
                  NetworkImageLoader(
                    imageUrl: widget.model.cover ?? '',
                    width: double.infinity,
                    height: double.infinity,
                  ),
                  Image.asset(
                    'circle_play.webp'.videoPath,
                    width: 30,
                    height: 30,
                  ),
                  if (needBuyPostVideo(widget.model) && hasClick)
                    Container(
                      constraints: BoxConstraints(maxWidth: double.infinity, maxHeight: 220),
                      decoration: BoxDecoration(color: Colors.black.withOpacity(.8), borderRadius: BorderRadius.circular(8)),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(isCoin ? '开通全网通VIP 永久免费观看' : '本视频需要开通 VIP 预览', style: textStyle(16, Colors.white, FontWeight.w400)),
                          16.verticalSpace,
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              GestureDetector(
                                onTap: () async {
                                  if (isCoin) {
                                    var result = await _onPay();
                                    if (result == true) {
                                      widget.model.vidStatus?.hasPaid = true;
                                      setState(() {});
                                      pushToPostVideoPage();
                                    }
                                  } else {
                                    jumpToWalletPage();
                                  }
                                },
                                child: Container(
                                  width: 120,
                                  height: 36,
                                  alignment: Alignment.center,
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(99),
                                      gradient: LinearGradient(colors: [Color(0xff64A4FF), Color(0xff004CFF)])),
                                  child: Text(
                                    isCoin ? '${widget.model.videoCoin()}金币解锁' : '前往开通VIP',
                                    style: textStyle(14, Colors.white, FontWeight.w400),
                                  ),
                                ),
                              ),
                              15.horizontalSpace,
                              GestureDetector(
                                onTap: () {
                                  if (isCoin) {
                                    jumpToWalletPage();
                                  } else {
                                    Get.to(() => MineSharePage());
                                  }
                                },
                                child: Container(
                                  width: 120,
                                  height: 36,
                                  alignment: Alignment.center,
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(99),
                                      gradient: LinearGradient(colors: [Color(0xffA84AFF), Color(0xff501FFF)])),
                                  child: Text(
                                    isCoin ? ' 开通全网通VIP' : '邀请好友得VIP',
                                    style: textStyle(14, Colors.white, FontWeight.w400),
                                  ),
                                ),
                              ),
                            ],
                          )
                        ],
                      ),
                    )
                ],
              ),
            ),
          ),
        ),
        if (widget.model.isSeedPost()) 10.sizeBoxH,
      ],
    );
  }
}

class PostDetailCoverContent extends StatefulWidget {
  final VideoModel model;

  const PostDetailCoverContent({super.key, required this.model});

  @override
  State<PostDetailCoverContent> createState() => _PostDetailCoverContentState();
}

class _PostDetailCoverContentState extends State<PostDetailCoverContent> {
  VideoModel get model => widget.model;

  @override
  Widget build(BuildContext context) {
    final length = model.showPicturesMaxLength();
    // model.seriesCover?.remove(model.cover);
    return Column(
      children: [
        if (length == 0)
          SizedBox.shrink()
        else
          ClipRRect(
            borderRadius: BorderRadius.circular(12),
            child: Wrap(
              runSpacing: 2,
              children: model.seriesCover!
                  .sublist(0, length)
                  .asMap()
                  .map(
                    (key, value) => MapEntry(
                        key,
                        GestureDetector(
                          behavior: HitTestBehavior.translucent,
                          onTap: () async {
                            // if (widget.model.coversPermission()|| key<4)
                            await Get.to(CommunityImagePage(
                              videoModel: widget.model,
                              index: key,
                            ));
                            setState(() {});
                          },
                          child: _buildNetImage(value,
                              borderRadius: 0,
                              width: double.infinity,
                              //测试说小于4张的都要显示，且不显示vip或购买的信息
                              hasPermission: (model.coversPermission() || length < 3) ? true : key != length - 1,
                              isGold: model.permission == 1,
                              height: 391),
                        )),
                  )
                  .values
                  .toList(),
            ),
          ),
        18.sizeBoxH,
      ],
    );
  }

  Widget _buildNetImage(String url,
      {double? width, double? height, bool isGold = false, double borderRadius = 8, bool hasPermission = false, bool isCover = true}) {
    return NetworkImageLoader(
      imageUrl: url,
      width: width,
      fit: BoxFit.fill,
      // calculateWidth: screen.screenWidth - 18.w*2,
      // placeSize: Size(screen.screenWidth , 280),
    );
  }

  List<Widget> _buildGoldHint(bool isGold, {bool isCover = true}) {
    return [
      if (isGold) ...[
        EasyRichText(
          '您只需花费 ${model.coins ?? 0} 金币',
          defaultStyle: TextStyle(color: Colors.white, fontSize: 22, fontWeight: FontWeight.w400),
          patternList: [
            EasyRichTextPattern(
                targetString: '${model.coins ?? 0}', style: TextStyle(color: Color(0xffDB361F), fontSize: 22, fontWeight: FontWeight.w500))
          ],
        ),
        20.sizeBoxH,
        Text(
          '即可解锁查看完整版',
          style: TextStyle(color: Colors.white.withOpacity(.6), fontSize: 12, fontWeight: FontWeight.w400),
        ),
      ] else ...[
        Text(
          '本内容需要开通VIP会员',
          style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w400),
        ),
        Text(
          '即可解锁查看完整版',
          style: TextStyle(color: Colors.white.withOpacity(.6), fontSize: 12, fontWeight: FontWeight.w400),
        ),
      ],
      18.sizeBoxH,
      GestureDetector(
        onTap: _buyAction,
        child: Container(
          height: 44,
          width: 155,
          alignment: Alignment.center,
          decoration: BoxDecoration(color: Color(0xffDB361F), borderRadius: BorderRadius.circular(22)),
          child: Text(
            isGold ? '立即解锁' : '开通会员',
            style: TextStyle(color: Colors.black, fontSize: 16, fontWeight: FontWeight.w500),
          ),
        ),
      )
    ];
  }

  _buyAction() async {
    final isGold = (model.permission == 1);

    if (!isGold) {
      await Get.to(MineChargeCoinPage(), preventDuplicates: false);
      setState(() {});
    } else {
      final res = await Get.bottomSheet(VideoBuyBottomSheet(videoM: widget.model), isScrollControlled: true);
      if (res == true) {
        widget.model.vidStatus?.hasPaid = true;
        setState(() {});
      }
    }
  }
}
